<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: 当燃 2016-01-09
 */
namespace app\mobile\controller;
use app\home\logic\UsersLogic;
use think\AjaxPage;
use think\Page;
use think\Db;
header("Content-Type: text/html; charset=utf8");
class Cellar extends MobileBase {

    public function index(){
        return $this->fetch();
    }

    /**
     * 分类列表显示
     */
    public function categoryList(){
    	$start = empty(I('start'))?0:I('start');
    	$limit = empty(I('limit'))?10:I('limit');
    	$nums = ceil($start/$limit);
    	if(IS_POST){
    		if(I('post.aroma_id')){
    			$aroma_id = (int)I('post.aroma_id');
    		}
    		if(I('post.type_id')){
    			$type_id = (int)I('post.type_id');
    		}
    		if(I('post.theme_id')){
    			$theme_id = (int)I('post.theme_id');
    		}
    		if(I('post.origin_id')){
    			$where['f.origin_id'] = (int)I('post.origin_id');
    		}
    		if(I('post.quantity')){
    			$where['b.quantity'] = array('LIKE','%'.(int)I('post.quantity').'%');
    		}
    	}
    	$where['a.type'] = 1;
    	$where['a.is_on_sale'] = 1;
    	

    	
    	$searchgoods = M('goods')->alias('a')
    	            ->field('a.*,b.*,f.suppliers_name')
			    	->join('cellar_goods_attr b','a.goods_id=b.goods_id')
			    	->join('suppliers f','f.suppliers_id=b.winery_id')
			    	->join('origin g','g.id=f.origin_id')
			    	->where($where)->order('a.shop_price')->select();
		//拼接属性数据  如果存在查询条件则按条件过滤
		foreach($searchgoods as $key=>$val){
			$searchgoods[$key]['aroma'] = M('cellar_aroma')->where('id','in',json_decode($val['aroma_id'],true))->field('title')->select();
			$searchgoods[$key]['cellartype'] = M('cellar_type')->where('id','in',json_decode($val['type_id'],true))->field('title')->select();
			$searchgoods[$key]['themeList'] = M('cellar_theme')->where('id','in',json_decode($val['theme_id'],true))->field('title')->select();
			if(!empty($searchgoods[$key]['themeList'])){
			     $searchgoods[$key]['themeList'] = array_slice($searchgoods[$key]['themeList'],0,2);
			}
			else{
				unset($searchgoods[$key]);
			}
			//兼容老数据
			if(is_array(json_decode($val['aroma_id'],true))){

			    if($aroma_id && !in_array($aroma_id,json_decode($val['aroma_id'],true))){
					unset($searchgoods[$key]);
				}	
			}
			else{
				if($aroma_id && $aroma_id != $val['aroma_id']){
					unset($searchgoods[$key]);
				}
			}
			
			if(is_array(json_decode($val['type_id'],true))){
			    if($type_id && !in_array($type_id,json_decode($val['type_id'],true))){
					unset($searchgoods[$key]);
				}
			}
			else{
				if($type_id && $type_id != $val['type_id']){
					unset($searchgoods[$key]);
				}
			}
			
			if(is_array(json_decode($val['theme_id'],true))){
				if($theme_id && !in_array($theme_id,json_decode($val['theme_id'],true))){
					unset($searchgoods[$key]);
				}
			}
			else{
				if($theme_id && $theme_id != $val['theme_id']){
					unset($searchgoods[$key]);
				}
			}
		}
			    
		$count = count($searchgoods);
		$pagesum = ceil($count/$limit);	   	   	
    	$aroma = M('cellar_aroma')->field('id,title')->select();//香型分类
    	$cellartype = M('cellar_type')->field('id,title')->select();//窖藏方式分类
    	$theme = M('cellar_theme')->field('id,title')->select();//主题分类
    	$origin = M('origin')->where('type',0)->field('id,title')->select();//原产地酒厂分类
    	$cellar_quantity = M('cellar_quantity')->field('id,val')->order('val')->select();//规格分类 

    	$searchgoods = array_chunk($searchgoods,$limit);

    	//print_r($searchgoods);
    	if(IS_POST){
    		if(!empty($searchgoods[$nums])){
	    		$return_arr = array(
	                    'status' => 1,
	                    'msg' => '请求成功',
	                    'data' => array('searchgoods'=>$searchgoods[$nums],'pagesum'=>$pagesum)
	                );
    		    return $this->ajaxReturn($return_arr);
    		}else{
	    		$return_arr = array(
	                    'status' => -1,
	                    'msg' => '没有数据',
	                    'data' => null
	                );
	    		return $this->ajaxReturn($return_arr);
	    	}	
    	}
    	$this->assign("limit",$limit);//每次取数据的条数
    	$this->assign("id",$id);
    	$this->assign('pagesum',$pagesum);
    	$this->assign('aroma',$aroma);
    	$this->assign('cellartype',$cellartype);
    	$this->assign('theme',$theme);
    	$this->assign('origin',$origin);
    	$this->assign('cellar_quantity',$cellar_quantity);
    	$this->assign('searchgoods',$searchgoods[$nums]);
    	
        return $this->fetch();
    }
    
    
    /**
     * 分类展示页面
     */
    public function category(){
    	$start = empty(I('start'))?0:I('start');
    	$limit = empty(I('limit'))?10:I('limit');
    	$nums = ceil($start/$limit);
    	$cateType = array(
    	          '1' => array('form'=>'cellar_aroma','name'=>'白酒香型','type'=>1),
    	          '2' => array('form'=>'cellar_type','name'=>'藏酒方式','type'=>2),
    	          '3' => array('form'=>'cellar_theme','name'=>'藏酒主题','type'=>3),
    	          '4' => array('form'=>'origin','name'=>'原产地','type'=>4),
    	          '5' => array('form'=>'cellar_quantity','name'=>'藏酒规格','type'=>5),
     	);
		$type = empty(I('type'))?1:(int)I('type');
		$id = empty(I('id'))?0:(int)I('id');
		if($type == 1 && !empty($id)){
			$aroma_id = $id;
		}
		if($type == 2 && !empty($id)){
			$type_id = $id;
		}
		if($type == 3 && !empty($id)){
			$theme_id = $id;
		}
		if($type == 4 && !empty($id)){
			$where = "f.origin_id = $id";
		}
		if($type == 5 && !empty($id)){
			$where = "b.quantity like '%$id%'";
		}
		
		if($type == 5){
			$categoryList = M($cateType[$type]['form'])->alias('a')->field('id,a.val as title')->select();
			$categoryName = M($cateType[$type]['form'])->alias('a')->field('id,a.val as title')->where(array('id'=>$id))->find();
		}elseif($type == 4){
		    $categoryList = M($cateType[$type]['form'])->where("type",0)->select();
		    $categoryName = M($cateType[$type]['form'])->where(array('id'=>$id))->find();
		}
		else{
		    $categoryList = M($cateType[$type]['form'])->select();	
		    $categoryName = M($cateType[$type]['form'])->where(array('id'=>$id))->find();
		}
		$goodsList = M('goods')->alias('a')
    	            ->field('a.*,b.*,f.suppliers_name')
			    	->join('cellar_goods_attr b','a.goods_id=b.goods_id')
			    	->join('suppliers f','f.suppliers_id=b.winery_id')
			    	->join('origin g','g.id=f.origin_id')->where($where)->where('a.is_on_sale=1')->order('a.shop_price')->select();
		//拼接属性数据  如果存在查询条件则按条件过滤
		foreach($goodsList as $key=>$val){
			$goodsList[$key]['aroma'] = M('cellar_aroma')->where('id','in',json_decode($val['aroma_id'],true))->field('title')->select();
			$goodsList[$key]['cellartype'] = M('cellar_type')->where('id','in',json_decode($val['type_id'],true))->field('title')->select();
			$goodsList[$key]['themeList'] = M('cellar_theme')->where('id','in',json_decode($val['theme_id'],true))->field('title')->select();
			//取前两位
			if(!empty($goodsList[$key]['themeList'])){
			    $goodsList[$key]['themeList'] = array_slice($goodsList[$key]['themeList'],0,2);
			}
			else{
				unset($goodsList[$key]);
			}
			//兼容老数据
			if(is_array(json_decode($val['aroma_id'],true))){
			    if($aroma_id && !in_array($aroma_id,json_decode($val['aroma_id'],true))){
					unset($goodsList[$key]);
				}	
			}
			else{
				if($aroma_id && $aroma_id != $val['aroma_id']){
					unset($goodsList[$key]);
				}
			}
			
			if(is_array(json_decode($val['type_id']))){
			    if($type_id && !in_array($type_id,json_decode($val['type_id'],true))){
					unset($goodsList[$key]);
				}
			}
			else{
				if($type_id && $type_id != $val['type_id']){
					unset($goodsList[$key]);
				}
			}
			
			if(is_array(json_decode($val['theme_id']))){
				if($theme_id && !in_array($theme_id,json_decode($val['theme_id'],true))){
					unset($goodsList[$key]);
				}
			}
			else{
				if($theme_id && $theme_id != $val['theme_id']){
					unset($goodsList[$key]);
				}
			}
		}
		
		$count = count($searchgoods);
		$pagesum = ceil($count/$limit);	
		$goodsList = array_chunk($goodsList,$limit);
			    	
		if(IS_AJAX){
    		if(!empty($goodsList)){
    	    	$return_arr = array(
                    'status' => 1,
                    'msg' => '请求成功',
                    'data' => $goodsList[$nums],
                    'pagesum' => $pagesum
	            );
        	}else{
	    		$return_arr = array(
                    'status' => -1,
                    'msg' => '没有数据',
                    'data' => $goodsList[$nums],
                    'pagesum' => $pagesum
                );
    	    }	
    	    return $this->ajaxReturn($return_arr);
		}
		//echo M('goods')->getLastSql();
		$this->assign('goodslist',$goodsList[$nums]); 	
    	$this->assign('categorylist',$categoryList);
    	$this->assign('categoryname',$categoryName);
    	$this->assign('theCate',$cateType[$type]);
    	$this->assign("type",$type);
    	$this->assign("id",$id);
    	
    	
    	$this->assign("pagesum",$pagesum);//传出总页数
    	$this->assign("limit",$limit);//每次取数据的条数
    	$this->assign("id",$id);
    	
        return $this->fetch();
    }
    
    
    /**
     * 窖藏主题列表显示
     */
    public function themeList(){

        return $this->fetch();
    }
     
    
    /**
     * 窖藏主题详情页面
     */
    public function theme(){
        $start = empty(I('start'))?0:I('start');
    	$limit = empty(I('limit'))?10:I('limit');
    	$pnum = ceil($start/$limit);
        $id=(int)I('id');
        $themeName = M('cellar_theme')->field('title')->where("id = $id")->find();
        $goodsList = M('goods')->alias('a')
                    ->field('a.*,b.*,f.suppliers_name')
                    ->join('cellar_goods_attr b','a.goods_id=b.goods_id')
                    ->join('suppliers f','f.suppliers_id=b.winery_id')
                    ->join('origin g','g.id=f.origin_id')
                    ->where("a.is_on_sale = 1")->order('a.shop_price')->select();           
        //拼接属性数据  如果存在查询条件则按条件过滤
		foreach($goodsList as $key=>$val){
			$goodsList[$key]['aroma'] = M('cellar_aroma')->where('id','in',json_decode($val['aroma_id'],true))->field('title')->select();
			$goodsList[$key]['cellartype'] = M('cellar_type')->where('id','in',json_decode($val['type_id'],true))->field('title')->select();
			$goodsList[$key]['cellartheme'] = M('cellar_theme')->where('id','in',json_decode($val['theme_id'],true))->field('title')->select();
            $theme_arr = json_decode($val['theme_id'],true);
			if(!is_array($theme_arr)) break;
			if(!in_array($id,$theme_arr) || empty($goodsList[$key]['aroma']) || empty($goodsList[$key]['cellartype']) || empty($goodsList[$key]['cellartheme'])){
				unset($goodsList[$key]);
			}
			else{
				$goodsList2[] = $goodsList[$key];
			}
		}
		$datasum = count($goodsList2);//总记录数
		$pagesum = ceil($datasum/$limit);//总记录数
		$goodsList2 = array_chunk($goodsList2, $limit,true); 
		
        if(IS_AJAX){
            if(!empty($goodsList2[$pnum])){
            	//print_r($goodsList2[$pnum]);        
                //exit;
                $return_arr = array(
                    'status' => 1,
                    'msg' => '请求成功',
                    'data' => $goodsList2[$pnum]
                );
            }else{
                $return_arr = array(
                    'status' => -1,
                    'msg' => '没有数据',
                    'data' => $goodsList2[$pnum]
                );
            }
            return $this->ajaxReturn($return_arr);
        }
        
        $this->assign("pagesum",$pagesum);//传出总页数
        $this->assign("limit",$limit);//每次取数据的条数
        $this->assign("id",$id);
        
        $this->assign('themename',$themeName);
        $this->assign('goodslist',$goodsList2[$pnum]);
        return $this->fetch();
    }
    
    
    /**
     * 窖藏方式列表显示
    */
    public function cellarType(){
        return $this->fetch();
    }
    
    /**
     * 白酒文化列表页
    */
    public function cultrue(){
        return $this->fetch();
    }
     /**
     * 白酒文化详情页
    */
    public function cultrueinfo(){
        $id=(int)I('id');
        $cultureinfo = M('cellar_culture')->where("id=$id")->find();
        $this->assign('cultureinfo',$cultureinfo);
        return $this->fetch();
    }
    
    /**
     * 最新活动
    */
    public function activity(){
    	
        return $this->fetch();
    }

 
    /*
     * 酒厂体验报名
     */
    public function activity_info(){
        $id = I("get.id");
        if(IS_POST){
            $id = I("post.activityID");
            $data['tid'] = I("post.activityID");
            $data['uid'] = $this->user_id;
            $data['name'] = I("post.name");
            $data['phone'] = I("post.tel");
            $data['num'] = I("post.sum");
            $data['addtime'] = time();
            $result = M('cellar_taste_form')->add($data);
            if($result){
                $this->success("报名成功","/mobile/User/activity_info/id/".$id);
            }else{
                $this->error("报名失败,请重试");
            }
        }
        $activityInfo = M("cellar_taste")->where("id",$id)->find();
        //获取报名报名信息
        $where['tid'] = $id;
        $where['uid'] = $this->user_id;
        $myActivityInfo = M("cellar_taste_form")->where($where)->find();
        if($myActivityInfo){
            $this->assign("isapply",1);
            $this->assign("myActivityInfo",$myActivityInfo);
        }else{
            $this->assign("isapply",0);
        }
        $this->assign("activityInfo",$activityInfo);
        return $this->fetch();
    }
    

    /**
     * 原产地酒厂
    */
    public function factory(){
        return $this->fetch();
    }
    
    /**
     * 原产地酒厂详情页
    */
    public function factoryInfo(){
        $start = empty(I('start'))?0:I('start');
    	$limit = empty(I('limit'))?10:I('limit');
        $id = (int)I('id');
        // 判断是否登录
        $user_id = $_SESSION['user']['user_id'];
//         if($user_id){
//             $follow_su = M('users')->field('follow_su')->where("user_id=$user_id")->find();
//             $array=explode(',',$follow_su['follow_su']);
//             if(in_array($id,$array)){
//                 $follow = 1;
//             }else{
//                 $follow = 0;
//             }
//         }
        //判断用户是否关注此酒厂
        $result = M('attention')->where(array('suppliers_id'=>$id,'user_id'=> $user_id))->find();
        if($result){
            $follow = 1;
        }else{
            $follow = 0;
        }
        
        $factoryInfo = M('suppliers')->where("suppliers_id=$id")->find();
        if($factoryInfo){
        	$factoryInfo['origin_name'] = M('origin')->where('id',$factoryInfo['origin_id'])->getField('title');
        }
        //流通商品
        $goodsList = M('goods')->where("suppliers_id = $id and type=0 and is_on_sale=1")->limit($start,$limit)->order("shop_price")->select();
        $cellar_goodsList = M('goods')->where("suppliers_id = $id and type=1 and is_on_sale=1")->limit($start,$limit)->order("shop_price")->select();
        $destine_goodsList = M('goods')->where("suppliers_id = $id and type=2 and is_on_sale=1")->limit($start,$limit)->order("shop_price")->select();

        $time = time();
//         //促销商品
//         $flash_sale = M("flash_sale")
//                       ->alias("fs")
//                       ->join("f_goods g","fs.goods_id = g.goods_id")
//                       ->join("f_suppliers s","s.suppliers_id = g.suppliers_id")
//                       ->where("s.suppliers_id = $id and fs.end_time >$time and fs.is_end =0")
//                       ->field("g.*")
//                       ->select();
//         //团购商品
//         $group_buy = M("group_buy")
//                       ->alias("gb")
//                       ->join("f_goods g","fs.goods_id = g.goods_id")
//                       ->join("f_suppliers s","s.suppliers_id = g.suppliers_id")
//                       ->where("s.suppliers_id = $id and gb.end_time >$time")
//                       ->field("g.*")
//                       ->select();
        
//         //一元夺宝
//         $indiana_sale = M("indiana_sale")
//                     ->alias("is")
//                     ->join("f_goods g","fs.goods_id = g.goods_id")
//                     ->join("f_suppliers s","s.suppliers_id = g.suppliers_id")
//                     ->where("s.suppliers_id = $id and is.end_time >$time and is.is_end =0")
//                     ->field("g.*")
//                     ->select();
        
//         //
        
//         echo M('goods')->getLastSql();
//                     拼接属性数据  如果存在查询条件则按条件过滤
// 		foreach($goodsList as $key=>$val){
// 		    if($val['type'] == 1){//窖藏商品
// 		        $goodsList['']
// 		    }elseif($val['type'] == 2){//定制商品
		        
// 		    }else{
		        
// 		    }
// 			$goodsList[$key]['aroma'] = M('cellar_aroma')->where('id','in',json_decode($val['aroma_id'],true))->field('title')->select();
// 			$goodsList[$key]['cellartype'] = M('cellar_type')->where('id','in',json_decode($val['type_id'],true))->field('title')->select();
// 			$goodsList[$key]['cellartheme'] = M('cellar_theme')->where('id','in',json_decode($val['theme_id'],true))->field('title')->select();
// 		}       
        $this->assign('follow',$follow);
        $this->assign('factoryinfo',$factoryInfo);
        $this->assign('goodslist',$goodsList);
        $this->assign('cellar_goodsList',$cellar_goodsList);
        $this->assign('destine_goodsList',$destine_goodsList);
        return $this->fetch();
    }

    /**
     * 原产地酒关注/取消登录
    */
    public function follow(){
        // 判断是否登录
        $user_id = $_SESSION['user']['user_id'];
        if(!$user_id){
            $this->error('请先登录',U('Mobile/Cellar/login'));
        }else{
            $suppliers_id = (int)I('post.suppliers_id');
            $is_follow = M('attention')->where(array('suppliers_id'=>$suppliers_id,'user_id'=> $user_id))->find();
            if($is_follow){
                $result = M('attention')->delete($is_follow['id']);
                if($result){//取消关注
                    $back['status'] = 2;
                    $back['msg'] = "取消关注成功";
                }else{
                    $back['status'] = 0;
                    $back['msg'] = "取消关注失败";
                }
            }else{//关注
                $data['suppliers_id'] = $suppliers_id;
                $data['user_id'] = $user_id;
                $data['addtime'] = time();
                $data['status'] = 1;
                $result = M('attention')->add($data);
                if($result){//取消关注
                    $back['status'] = 1;
                    $back['msg'] = "关注成功";
                }else{
                    $back['status'] = 0;
                    $back['msg'] = "关注失败";
                }
            }
            echo json_encode($back);
            exit();
        }
        // return $this->fetch();
    }



    
    /**
     * 体验报名
    */
    public function tasteForm(){
        return $this->fetch();
    }

    /**
     * 商品列表页
     */
    public function goodsList(){
        $id = I('get.id',0); // 当前分类id
        $lists = getCatGrandson($id);
        $this->assign('lists',$lists);
        return $this->fetch();
    }
    
    
    /**
     * 商品详情页
     */
    public function goodsInfo(){
    	
        C('TOKEN_ON',true);        
        $goodsLogic = new \app\home\logic\GoodsLogic();
        $goods_id = I("get.id");
        $goods = M('Goods')->where("goods_id", $goods_id)->find();       
        if(empty($goods)){      	
        	$this->error('此商品不存在或者已下架');
        }
        $goods = M('goods')->alias('a')
                         ->join('cellar_goods_attr b','b.goods_id = a.goods_id')
                         ->join('suppliers f','b.winery_id = f.suppliers_id')
                         ->join('origin g','g.id = f.origin_id')
                         ->field('a.*,b.*,f.suppliers_logo,g.title as originname,f.suppliers_address,
                         f.suppliers_name,f.custodian_fee,f.brand_name,f.suppliers_logo,f.suppliers_id')
                         ->where('b.goods_id',$goods_id)->find();
		$goods['aroma'] = M('cellar_aroma')->where('id','in',json_decode($goods['aroma_id'],true))->field('title')->select();
		$goods['cellartype'] = M('cellar_type')->where('id','in',json_decode($goods['type_id'],true))->field('title')->select();
		$goods['cellartheme'] = M('cellar_theme')->where('id','in',json_decode($goods['theme_id'],true))->field('title')->select();
		                  
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册

        $cellar_quantity = M('cellar_quantity')->select();//窖藏规格
        if(!empty($goods['quantity'])){//若未选择，则默认最低本店价,最低市场价
        	$goods['quantity'] = json_decode($goods['quantity'],true);
        	foreach ($cellar_quantity as $key=>$value){
        	    if(!empty($goods['quantity']['val'])){
            	    foreach ($goods['quantity']['val'] as $k=>$v){
            	        if($value["id"] == $v){
            	            $date['id'] = $value["id"];
            	            $date['val'] = $value['val'];
            	            $date['price'] = $goods['quantity']['price'][$v];
            	            $quantity[] = $date;
            	        }
            	    }
        	    }
        	}
        }
        else{
        	$quantity[] = $cellar_quantity[1];
        	$quantity[0]['price'] = $goods['shop_price'];
        }
        
//     	$goods['sale_num'] = M('order_goods')->where(['goods_id'=>$goods_id,'is_send'=>1])->count();
        
        //取10条评论消息
        $comment_list = M("comment")
                        ->alias("c")
                        ->join("f_users u","c.user_id = u.user_id","left")
                        ->where(array("c.goods_id" =>$goods_id,"c.is_show"=>1))
                        ->order("c.add_time desc")
                        ->field("c.*,u.head_pic")
                        ->limit(10)
                        ->select();
        foreach ($comment_list as $key => $value){
            $comment_list[$key]['img'] = unserialize($value['img']);
        }
        $this->assign('comment_list',$comment_list);
        $this->assign('goods_images_list',$goods_images_list);//商品缩略图
        $this->assign('goods',$goods);
        $this->assign('aromaname',$goods['aroma'][0]['title']);
        $this->assign('quantity',$quantity);//窖藏规格
        return $this->fetch();
    }
    
    
    
    public function ajaxGetMore(){
    	$p = I('p/d',1);
    	$favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale=1")->order('goods_id DESC')->page($p,10)->cache(true,TPSHOP_CACHE_TIME)->select();//首页推荐商品
    	$this->assign('favourite_goods',$favourite_goods);
    	return $this->fetch();
    }

    // 促销活动页面
    public function promoteList()
    {
        $goodsList = DB::query("select * from __PREFIX__goods as g inner join __PREFIX__flash_sale as f on g.goods_id = f.goods_id   where ".time()." > start_time  and ".time()." < end_time");
        $brandList = M('brand')->limit(5)->getField("id,name,logo");
        $this->assign('brandList',$brandList);
        $this->assign('goodsList',$goodsList);
        return $this->fetch();
    }

    // 加载更多促销活动商品
    public function ajaxPromoteList(){
        $p = ((I('p/d')*5))+1;
        $goodsList = DB::query("select * from __PREFIX__goods as g inner join __PREFIX__flash_sale as f on g.goods_id = f.goods_id   where ".time()." > start_time  and ".time()." < end_time");
        $brandList = M('brand')->page($p,5)->getField("id,name,logo");
        $this->assign('brandList',$brandList);
        $this->assign('goodsList',$goodsList);
        return $this->fetch();
    }

}